package service

import (
	"github.com/jinzhu/gorm"
	"github.com/xdhuxc/asset-management-system/src/model"
	"time"
)

type transactionService struct {
	db *gorm.DB
}

func newTransactionService(db *gorm.DB) *transactionService {
	return &transactionService{db}
}

func (ts *transactionService) Create(btd *model.BankTransactionDetails) (*model.BankTransactionDetails, error) {
	if err := btd.Validate(); err != nil {
		return btd, err
	}

	btd.CreateTime = time.Now()
	btd.UpdateTime = time.Now()
	if err := ts.db.Model(&model.BankTransactionDetails{}).Create(btd).Error; err != nil {
		return btd, err
	}

	return btd, nil
}

func (ts *transactionService) Delete(btdID int64) error {
	return ts.db.Model(&model.BankTransactionDetails{}).Where("id = ?", btdID).Delete(model.BankTransactionDetails{}).Error
}

func (ts *transactionService) Update(btd *model.BankTransactionDetails) (*model.BankTransactionDetails, error) {
	if err := btd.Validate(); err != nil {
		return btd, err
	}

	btd.UpdateTime = time.Now()
	if err := ts.db.Model(&model.BankTransactionDetails{}).Update(map[string]interface{}{
		"date":                   btd.Date,
		"type":                   btd.Type,
		"bank_card":              btd.BankCard,
		"income":                 btd.Income,
		"expenditure":            btd.Expenditure,
		"balance":                btd.Balance,
		"remark":                 btd.Remark,
		"additional_description": btd.AdditionalDescription,
		"create_time":            btd.CreateTime,
		"update_time":            btd.UpdateTime,
	}).Error; err != nil {
		return btd, err
	}

	return btd, nil
}

func (ts *transactionService) Get(btdID int64) (*model.BankTransactionDetails, error) {
	var btd *model.BankTransactionDetails

	if err := ts.db.Model(&model.BankTransactionDetails{}).
		Where("id = ?", btdID).First(&btd).Error; err != nil {
		return btd, err
	}

	return btd, nil
}

func (ts *transactionService) List(page model.Page) (int64, []model.BankTransactionDetails, error) {
	var count int64
	var btds []model.BankTransactionDetails

	if err := ts.db.Model(&model.BankTransactionDetails{}).
		Count(&count).
		Offset(page.Offset).
		Limit(page.PageSize).
		Order("update_time desc").
		Find(&btds).Error; err != nil {
		return count, btds, err
	}

	return count, btds, nil
}
